package index;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String inputCaptcha = request.getParameter("captcha");
        String sessionCaptcha = (String) request.getSession().getAttribute("CAPTCHA");

        // 验证码校验
        if (!inputCaptcha.equalsIgnoreCase(sessionCaptcha)) {
            request.setAttribute("loginError", "验证码错误");
            request.getRequestDispatcher("loginRegister.jsp").forward(request, response);
            return;
        }

        // MD5加密（与注册保持一致）
        String hashedPwd = md5(password);

        // 数据库验证
        if (JdbcUtils.validateUser(username, hashedPwd)) {
            HttpSession session = request.getSession();
            session.setAttribute("username", username);
            String role = JdbcUtils.getUserRole(username);


            session.setAttribute("role", role);
            response.sendRedirect("WelcomeServlet");
        } else {
            request.setAttribute("loginError", "用户名或密码错误");
            request.getRequestDispatcher("loginRegister.jsp").forward(request, response);
        }
        System.out.println("输入的密码: " + password);
        System.out.println("加密后的密码: " + hashedPwd);
    }

    private String md5(String input) {
        // 保持与注册相同的加密逻辑
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : array) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
            return input;
        }
    }
}
